package com.xizi.lotterySystem.service.Impl;

import com.xizi.lotterySystem.common.exception.ServiceException;
import com.xizi.lotterySystem.common.exception.errorCode.ServiceErrorCodeConstants;
import com.xizi.lotterySystem.controller.param.PageListParam;
import com.xizi.lotterySystem.controller.param.PrizeCreateParam;
import com.xizi.lotterySystem.controller.result.PrizeInfo;
import com.xizi.lotterySystem.dao.mapper.PrizeMapper;
import com.xizi.lotterySystem.service.IPictureService;
import com.xizi.lotterySystem.service.IPrizeService;
import com.xizi.lotterySystem.dao.dataobject.PrizeDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class PrizeServiceImpl implements IPrizeService {

    private static final Logger log = LoggerFactory.getLogger(PrizeServiceImpl.class);
    @Autowired
    private PrizeMapper prizeMapper;

    @Autowired
    private IPictureService pictureService;

    @Override
    public Long create(PrizeCreateParam param, MultipartFile file) {
        //1.保存图片
        String path = pictureService.savePicture(file);

        //2.构建奖品DO对象
        PrizeDO prizeDO = new PrizeDO();
        prizeDO.setName(param.getPrizeName());
        prizeDO.setDescription(param.getDescription());
        prizeDO.setPrice(param.getPrice());
        prizeDO.setImageUrl(path);
        //3.进行插入
        int row = prizeMapper.insertPrize(prizeDO);

        if(row != 1){
            throw new ServiceException(ServiceErrorCodeConstants.SQL_ERROR);
        }
        return prizeDO.getId();
    }

    @Override
    public Long getPrizeCount() {
         long count = prizeMapper.selectPrizeCount();
         return count;
    }

    @Override
    public List<PrizeInfo> getPrizeList(PageListParam param) {
        if(param == null || param.getPageSize() <= 0 || param.getCurrentPage() <= 0){
            log.error("ServiceException getPrizeList param:{}", param);
            throw new ServiceException(ServiceErrorCodeConstants.PARAM_ERROR);
        }
        List<PrizeDO> list = prizeMapper.selectPrizeList(param);

        List<PrizeInfo> prizeInfoList = new ArrayList<>();
        for(PrizeDO prizeDO : list){
            PrizeInfo prizeInfo = new PrizeInfo();
            prizeInfo.setPrizeId(prizeDO.getId());
            prizeInfo.setPrizeName(prizeDO.getName());
            prizeInfo.setDescription(prizeDO.getDescription());
            prizeInfo.setPrice(prizeDO.getPrice());
            prizeInfo.setImageUrl(prizeDO.getImageUrl());
            prizeInfoList.add(prizeInfo);
        }

        return prizeInfoList;
    }
}
